#pragma once
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "Log.hpp"

// 处理命令
class Command
{
    std::vector<std::string> white_list = {"ls", "touch"};

public:
    Command(std::string command)
        : _command(command)
    {
    }
    bool CheckCommand()
    {
        for (auto s : white_list)
        {
            if (strncmp(_command.c_str(), s.c_str(), s.size()) == 0)
                return true;
        }
        return false;
    }
    std::string HandlerCommand()
    {
        if (!CheckCommand())
        {
            return "command errer";
        }
        FILE *fp = popen(_command.c_str(), "r");
        if (fp == nullptr)
        {
            LOG(FATAL, "popen fail");
        }
        std::string result;
        char line[1024] = {0};
        while (fgets(line, sizeof(line), fp)) // 获取一行包含了\n\0
        {
            result += line;
            // memset(line, 0, sizeof(line)); // 重置一下
        }
        pclose(fp);

        return result.empty() ? "command success" : result;
    }

private:
    std::string _command;
};